<?php
declare(strict_types=1);
namespace SixShop\MakerBundle;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Style\SymfonyStyle;
use SixShop\MakerBundle\Generator\ComposerGenerator;
use SixShop\MakerBundle\Generator\DirectoryGenerator;
use SixShop\MakerBundle\Generator\GitignoreGenerator;
use SixShop\MakerBundle\Generator\PhpCodeGenerator;

class Maker extends Command
{
    protected static $defaultName = 'create_extension';
    protected static $defaultDescription = '创建SixShop扩展';

    private ComposerGenerator $composerGenerator;
    private DirectoryGenerator $directoryGenerator;
    private GitignoreGenerator $gitignoreGenerator;
    private PhpCodeGenerator $phpCodeGenerator;
    
    public function __construct()
    {
        parent::__construct();
        $this->composerGenerator = new ComposerGenerator();
        $this->directoryGenerator = new DirectoryGenerator();
        $this->gitignoreGenerator = new GitignoreGenerator();
        $this->phpCodeGenerator = new PhpCodeGenerator();
        $this->setAliases(['ce']);
    }

    protected function configure(): void
    {
        $this->setName('create_extension')
             ->setDescription(self::$defaultDescription);
    }
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);
        
        // 获取用户输入的目标路径
        $targetPath = $this->getTargetPath($io);
        if (!$targetPath) {
            return Command::FAILURE;
        }
        
        // 获取用户输入的包信息（现在会检测目标路径下的composer.json）
        $packageInfo = $this->composerGenerator->gatherPackageInfo($io, $targetPath);
        if (!$packageInfo) {
            return Command::FAILURE;
        }
        
        // 生成 composer.json 文件
        $io->section('生成 composer.json 文件');
        if (!$this->composerGenerator->createComposerJson(
            $packageInfo['packageName'],
            $packageInfo['namespace'],
            $packageInfo['id'],
            $packageInfo['description'],
            $targetPath,
            $io
        )) {
            return Command::FAILURE;
        }
        
        // 创建目录结构
        $io->section('创建目录结构');
        if (!$this->directoryGenerator->createDirectoryStructure($packageInfo['packageName'], $targetPath, $io)) {
            return Command::FAILURE;
        }
        
        // 生成 .gitignore 文件
        $io->section('生成 .gitignore 文件');
        if (!$this->gitignoreGenerator->createGitignore($packageInfo['packageName'], $targetPath, $io)) {
            return Command::FAILURE;
        }
        
        // 生成 PHP 代码文件
        $io->section('生成 PHP 代码文件');
        if (!$this->phpCodeGenerator->generatePhpFiles(
            $packageInfo['packageName'],
            $packageInfo['namespace'],
            $packageInfo['id'],
            $packageInfo['description'],
            $targetPath,
            $io
        )) {
            return Command::FAILURE;
        }
        
        $io->success('扩展创建完成!');
        return Command::SUCCESS;
    }
    
    /**
     * 获取用户输入的目标路径
     */
    private function getTargetPath(SymfonyStyle $io): ?string
    {
        try {
            // 获取当前工作目录作为默认值
            $defaultPath = getcwd();
            
            $targetPath = $io->ask(
                '请输入扩展生成的目标路径 (绝对路径或相对路径)',
                $defaultPath
            );
            
            if (empty($targetPath)) {
                throw new \InvalidArgumentException('目标路径不能为空!');
            }
            
            // 转换为绝对路径
            $absolutePath = realpath($targetPath);
            if ($absolutePath === false) {
                // 如果路径不存在，尝试创建它
                if (!is_dir($targetPath)) {
                    $io->note('目标路径不存在，尝试创建目录: ' . $targetPath);
                    if (!mkdir($targetPath, 0755, true)) {
                        throw new \InvalidArgumentException('无法创建目标路径: ' . $targetPath);
                    }
                }
                $absolutePath = realpath($targetPath);
            }
            
            // 检查路径是否可写
            if (!is_writable($absolutePath)) {
                throw new \InvalidArgumentException('目标路径不可写: ' . $absolutePath);
            }
            
            $io->note('将在以下路径生成扩展: ' . $absolutePath);
            
            // 确认路径
            if (!$io->confirm('确认使用此路径?', true)) {
                return $this->getTargetPath($io); // 递归重新获取路径
            }
            
            return $absolutePath;
            
        } catch (\InvalidArgumentException $e) {
            $io->error($e->getMessage());
            return null;
        }
    }
}